package Web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.ConnectToDB;

/**
 * Servlet implementation class Registration
 */
public class Registration extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 doPost(request, response);
		 return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		
		PreparedStatement stmt = null;
		Connection con = null;
		ResultSet res = null;
		
		//get parameters from registration form
		
		String user = request.getParameter("username")=="" ? null : request.getParameter("username");
		String pass = request.getParameter("password")=="" ? null : request.getParameter("password");
		String firstName = request.getParameter("firstName")=="" ? null : request.getParameter("firstName");
		String lastName = request.getParameter("lastName")=="" ? null : request.getParameter("lastName");
		String phone = request.getParameter("number")=="" ? null : request.getParameter("number");
		String admin = request.getParameter("choice")=="" ? null : request.getParameter("choice");
		String code = request.getParameter("code")=="" ? null : (String) request.getParameter("code");
		
		//Check input - server side!
		
		if (null == pass || 
			null == user || 
			null == firstName ||
			null == lastName ||
			pass.length() > 8 || 
			user.length() > 8 ||
			firstName.length() > 15 ||
			lastName.length() > 15 ||
			phone.length() > 15 ||
			!(phone.matches("[0-9]+"))){
			
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
			
			}
	
		try {
			
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			
			//admin account 
			if (admin.equals("yes")){
				if (!p.getProperty("adminCode").equals(code)){
					request.getSession().setAttribute("wrongCode", "yes");
					response.sendRedirect("registration.jsp");
					return;
				}
			}
			
			//create connection
			con = (new ConnectToDB(p)).getConnection();
			
			//check if username exist
			stmt = con.prepareStatement("SELECT * from user where username = ? ");
			stmt.setString(1, user);
			res = stmt.executeQuery(); 
				
			if (res.next()){
				request.getSession().setAttribute("usernameExist", "yes");
				response.sendRedirect("registration.jsp");
				return;
			} 
			
			//register user
			 stmt = con.prepareStatement("INSERT INTO user (username, password, first_name, last_name, phone_number, administrator) " +
				"VALUES(?,?,?,?,?,?)");
			 
			 stmt.setString(1, user);
			 stmt.setString(2, pass);
			 stmt.setString(3, firstName);
			 stmt.setString(4, lastName);
			 stmt.setString(5, phone);
			 stmt.setBoolean(6, (admin.equals("yes")));
			 
			 stmt.executeUpdate();
			 
			 
			 //goto login
			 response.sendRedirect("index.jsp");
		}
		
		catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
			
		finally { // Close the connection.
				if(res!=null){
				     try{res.close();}	catch(Exception e){e.printStackTrace();} }
				if(stmt !=null){
				     try{stmt.close();}	catch(Exception e){e.printStackTrace();} }
				if(con !=null){
				     try{con.close();}	catch(Exception e){e.printStackTrace();} }
				}
	}
	
}
